package fwk;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class BeanFactory {
	private String factoryName;
	private Map<String, Object> beansMap=new HashMap<String, Object>();
	
	public Object getBean(String beanName){
		return beansMap.get(beanName);
	}
	private  void parseAndCreateBeans() throws Exception{
		Document doc= new SAXBuilder().build(factoryName);
		List<Element> beanEles=doc.getRootElement().getChildren("bean");
		for(Element be:beanEles){
			String name=be.getAttributeValue("name");
			String className=be.getAttributeValue("class");
			Object o=Class.forName(className).newInstance();
			if(o instanceof HandlerMapping){
				name="handlerMapping";
			}
			if(o instanceof HandlerAdapter){
				name="handlerAdapter";
			}
			if(o instanceof ViewResolver){
				name="viewResolver";
			}
			beansMap.put(name, o);
			
		}
	}
	private void fillHandlerMapping(){
		HandlerMapping hanlerMapping=(HandlerMapping)beansMap.get("handlerMapping");
		for(String k:beansMap.keySet()){
			if(beansMap.get(k) instanceof Controller){
				hanlerMapping.addController(k, (Controller)beansMap.get(k));
			}
		}
	}
	public BeanFactory(String factoryName) {
		this.factoryName = factoryName;
		try {
			parseAndCreateBeans();
			fillHandlerMapping();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws Exception{
		BeanFactory bf = new BeanFactory("applicationContext.xml");
		bf.parseAndCreateBeans();
	}
}
